#include<iostream>
#include<pthread.h>
#include<string>
#include<unistd.h>


using namespace std;

int tickets = 1000;
pthread_mutex_t mutex;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *threadrun(void *argv)
{
    string name = static_cast<char*>(argv);
    delete[] static_cast<char*>(argv);
    
    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        if (tickets > 0)
        {
            usleep(1000);
            cout << name << " get a ticket " << tickets-- << endl;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }

        usleep(1000);
    }
    

    return nullptr;
}

int main()
{

    pthread_t t[5];
    pthread_mutex_init(&mutex,nullptr);
    int n = sizeof(t)/sizeof(t[0]);

    for(int i = 0 ; i < n ;i++ )
    {
        char *name = new char[64];
        snprintf(name,64,"thread-%d",i+1);
        pthread_create(t+i,nullptr,threadrun,name);
        //delete[] name;
    }

    sleep(3);
    int cont = 100;
    while(cont--)
    {
        cout<<"main thread wakeup"<<endl;
        //pthread_cond_signal(&cond);//只唤醒单独一个条件变量
        pthread_cond_broadcast(&cond);//给全部的条件变量唤醒
        sleep(1);
    }


    for (int i = 0; i < n; i++)
    {
        
        pthread_join(t[i],nullptr);
    }
    pthread_mutex_destroy(&mutex);


    return 0;
}